<template>
   <div class="user-address">
      <!-- 页面标题 -->
      <HeaderTop title="结算页">
         <span
            class="iconfont icon-jiantou2"
            slot="left"
            @click="$router.back()"
         ></span>
      </HeaderTop>
      <!-- 添加收货地址 -->
      <van-contact-card add-text="添加收货地址" type="add" @click="addAddress" />
      <!-- 添加地址的模态框 -->
      <div class="modal" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" :class="{'fade in': ishowModal, 'fade': !ishowModal}">
         <div class="modal-dialog" role="document">
            <div class="modal-content">
               <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close" @click="cancelAddress"><span aria-hidden="true">×</span></button>
                  <h4 class="modal-title" id="exampleModalLabel">{{isUpdate?'更新收货地址':'添加收货地址'}}</h4>
               </div>
               <div class="modal-body">
                  <form>
                     <div class="form-group">
                        <label for="recipient-name" class="control-label">姓名</label>
                        <input type="text"
                           class="form-control"
                           id="recipient-name"
                           v-model="currentContact.realname"
                        />
                     </div>
                     <div class="form-group">
                        <label for="recipient-name" class="control-label">电话</label>
                        <input type="text"
                           class="form-control" 
                           id="recipient-name"
                           v-model="currentContact.phone"
                        />
                     </div>
                     <div class="form-group">
                        <label for="recipient-name" class="control-label">收货地址</label>
                        <input type="text" 
                           class="form-control" 
                           id="recipient-name"
                           v-model="currentContact.address"
                        />
                     </div>
                  </form>
               </div>
               <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal" @click="cancelAddress">取消</button>
                  <button type="button" class="btn btn-primary" @click="saveAddress">{{ isUpdate?'修改':'添加' }}</button>
               </div>
            </div>
         </div>
      </div>
      <section>
         <!-- 收货地址栏的标题 -->
         <div class="title-bar">
            <i class="iconfont icon-xuanxiang"></i>
            <span class="title">收货地址</span>
         </div>
         <!-- 收货地址列表 -->
         <div class="address-list">
            <AddressCard
               v-for="(item, index) of addressList"
               :key="index"
               :checked="addressActive === index + 1"
               :index="index + 1"
               :id="item.id"
               :item="item"
               @event="_changeRibbon"
            />
         </div>
      </section>
      <!-- 商品菜单列表 -->
      <section class="foods-box">
         <!-- 所购食品列表的标题栏 -->
         <div class="title-bar">
            <i class="iconfont icon-xuanxiang"></i>
            <span class="title">所购食品</span>
         </div>
         <!-- 食品列表 -->
         <ul class="foods-list">
            <li class="foods-item" v-for="item of myGoods" :key="item.id">
               <span class="food-name">{{item.foodname}}</span>
               <div class="food-info">
                  <span class="food-price">￥{{item.price}}</span>
                  <span class="food-count">x{{item.count}}</span>
               </div>
            </li>
         </ul>
      </section>
      <!-- 点击地址时弹出的功能区 -->
      <van-popup v-model="showRibbon" position="right" :style="{ height: '100%',width: '25%' }">
         <button class="btn btn-primary" @click="editAddress"><van-icon name="notes-o"/>修改</button>
         <button class="btn btn-danger"><van-icon name="delete-o" @click="delAddress"/>删除</button>
      </van-popup>
      <!-- 底部结算区 -->
      <div class="add-to-order">
         <span class="total-money" :class="{'money-enough': addressActive}">总计：￥{{getTotalMoney}}</span>
         <div class="pay" :class="{enough: addressActive, 'not-enough': !addressActive}" @click="addOrder">结算</div>
      </div>
   </div>
</template>

<script>
import HeaderTop from "@/components/HeaderTop/HeaderTop";
import AddressCard from "@/components/AddressCard/AddressCard";
//vuex
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
//vant
import { Dialog } from 'vant';
//mui
import { MessageBox, Toast } from 'mint-ui';
//ajax
import { insertOneAddress, delOneAddress, updateOneAddress, insertOrder } from '@/api/ajax'

export default {
   components: {
      HeaderTop,
      AddressCard,
   },
   data() {
      return {
         currentContact: {
            id: null, // 收货地址id
            username: '', // 收货人网名
            realname: '', // 收货人真实姓名
            phone: '', // 收货人手机号
            address: '', // 收货人收货地址
         },
         ishowModal: false, // 是否显示模态框
         showRibbon: false, // 是否展示左侧的功能区域
         isUpdate: false, // 是否处于更新状态
         myaddress: {}, // 点击某项地址栏时临时存储点击的地址数据
      };
   },
   computed: {
      ...mapState('profile', ['userInfo']),
      ...mapState('account', ['addressActive', 'myGoods', 'addressList', 'newAddress']),
      ...mapGetters('account', ['getTotalMoney'])
   },
   mounted() {
      // 获取当前用户的收货地址
      this.getAddressList(this.userInfo.username)
      // 初始化模态框的位置
      document.getElementById('exampleModal').style['z-index'] = '-999'
   },
   methods: {
      ...mapActions('account', ['getAddressList']),
      ...mapMutations('account', ['DEL_ADDRESS_FROM_ADDRESSLIST', 'ADD_ADDRESS_TO_ADDRESSLIST', 'UPDATE_ADDRESSLIST_BY_ID', 'CLEAR_STATE', 'TOGGLE_ADDRESS_ACTIVE']),
      /* 点击添加一条新地址 */
      addAddress() {
         for (let key in this.currentContact) {
            this.currentContact[key] = ''
         }
         this.isUpdate = false // 处于非更新状态
         this.showMymodal()
      },
      /* 添加到我的订单页面 */
      addOrder() {
         let text = ''
         if (this.addressList.length) { text = '请选择收货地址后重试' }
         else { text = '请添加地址后重试' }
         if (!this.addressActive) return Dialog({ message: text })
         const addressObj = this.addressList[this.addressActive - 1]
         const order = {
            address_id: addressObj.id,
            food_totalprice: this.getTotalMoney,
            username: addressObj.username,
            goods: this.myGoods,
            time: new Date(),
            shopname: this.myGoods[0].shopname,
            shoplist_id: this.myGoods[0].shoplist_id
         }
         // 将数据传到服务器创建订单
         insertOrder(order).then(({msg}) => {
            if (msg !== 'ok') return Dialog({ message: '订单添加失败' })
            Toast('订单添加成功')
            // 跳转到订单页面
            setTimeout(() => {
               this.$router.replace('/order')
            }, 200);
         })
      },
      /* 新增一条收货地址 */
      saveAddress() {
         this.hiddenMymodal()
         const newAddress = {
            ...this.currentContact,
            username: this.userInfo.username
         }
         let text = this.isUpdate ? '更新' : '添加'
         if (!this.isUpdate) {
            // 提交新添加的地址到服务器并存储【添加操作】
            insertOneAddress(newAddress).then(({msg, insertId}) => {
               if (msg !== 'ok') return Dialog({ message: `地址${text}失败` })
               newAddress.id = insertId
               this.ADD_ADDRESS_TO_ADDRESSLIST(newAddress) // 添加成功后更新状态中的数据
               Dialog({ message: `地址${text}成功` })
            })
         } else {
            // 更新数据中的数据
            updateOneAddress(newAddress).then(({msg}) => {
               if (msg !== 'ok') return Dialog({ message: `地址${text}失败` })
               this.UPDATE_ADDRESSLIST_BY_ID(newAddress) // 更新成功后修改状态中的那条数据
               Dialog({ message: `地址${text}成功` })
            })
         }
      },
      /* 取消保存新添加的收货地址 */
      cancelAddress() {
         this.hiddenMymodal()
      },
      /* 删除一条收货地址 */
      delAddress() {
         const { id: addressId } = this.myaddress
         this.showRibbon = false //隐藏右侧功能区
         MessageBox.confirm('您确定删除该收货地址吗?').then(() => {
            // 执行删除地址操作
            delOneAddress(addressId).then(({msg}) => {
               if (msg !== 'ok') return Toast('删除失败')
               Toast('删除成功')
               this.DEL_ADDRESS_FROM_ADDRESSLIST(addressId)
               this.TOGGLE_ADDRESS_ACTIVE(null)
            })
         }, () => {});
      },
      /* 隐藏模态框 */
      hiddenMymodal() {
         this.ishowModal = false
         setTimeout(() => {
            document.getElementById('exampleModal').style['z-index'] = '-999'
         }, 200)
      },
      /* 显示模态框 */
      showMymodal() {
         document.getElementById('exampleModal').style['z-index'] = ''
         this.ishowModal = true
      },
      /* 点击收货地址展示右侧的功能区 */
      _changeRibbon(myaddress) {
         this.myaddress = myaddress
         this.showRibbon = true
      },
      /* 点击编辑地址 */
      editAddress() {
         for (let key in this.currentContact) {
            this.currentContact[key] = this.myaddress[key]
         }
         this.showRibbon = false
         this.isUpdate = true // 处于更新状态
         this.showMymodal()
      }
   }
};
</script>

<style lang="stylus" scoped>
@import 'bootstrap/dist/css/bootstrap.min.css';
.van-contact-card {
   padding: 10px;
}

#exampleModal {
   position fixed;
   top: 0;
   left: 0;
   background: rgba(0,0,0,.5)
   overflow: hidden;
   display: block;
}
#exampleModal.in {
   z-index: 666 !important;
}

.v-enter-active {
   animation: move .5s;
}
.v-leave-active {
   animation: move .5s reverse; 
}
@keyframes move {
   from {
      opacity: 0;
   } to {
      opacity: 1;
   }
}

.user-address {
   padding-top: 45px;
   padding-bottom: 56px;
   .icon-jiantou2 {
      color: #fff;
   }
}

section {
   width: 97%;
   margin: 0 auto;
   margin-top: 7px;
}

.title-bar {
   width: 100%;
   padding: 10px;
   box-sizing: border-box;
   background: #fff;
   font-size: 16px;
   color: #999;
}

/* 收货地址列表 */
.address-list {
   background-color: #fff;
}

/* 添加到订单区 */
.add-to-order {
   width: 100%;
   max-width: 750px;
   height: 56px;
   background-color: #141d27;
   position: fixed;
   bottom: 0;
   left: 50%;
   transform: translateX(-50%);
   display: flex;
   justify-content: space-between;
   align-items: center;
   box-sizing: border-box;
   font-size: 12px;
   .total-money { 
      margin-left: 10px;
      color: #80858a;
   }
   .money-enough { color: #fff;}
   .pay {
      width: 105px;
      height: 100%;
      line-height: 56px;
      text-align: center;
      font-weight: 700;
   }
   .enough {
      color: #fff;
      background: #00b43c;
      cursor pointer
   }
   .not-enough {
      color: #80858a;
      background: #2b333b;
   }
}

/* 食品列表 */
.foods-box {
   font-size: 14px;
   .title-bar {
      position: relative;
      &::before {
         content: '';
         position: absolute;
         left: 50%;
         bottom: 0;
         width: 95%;
         height: 1px;
         background-color: rgba(7,17,27,0.1);
         transform: scaleY(0.5) translateX(-50%);
      }
   }
}
.foods-list {
   padding: 5px 5px;
   background: #fff;
   .foods-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 5px 8px;
      box-sizing: border-box;
      background: #fff;
   }
   .food-info {
      display: flex;
      align-items: center;
      color: #333;
      .food-count {
         margin-left: 10px;
      }
   }
}

.van-popup {
   display: flex;
   flex-direction: column;
   >button {
      width: 100%;
      padding: 10px 0;
      border-radius: 0;
   }
   .van-icon {
      margin: 0 2px;
   }
}
</style>